package cn.qayy.utils;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import cn.qayy.constants.Constant;
import cn.qayy.dto.KuCunItem;
import cn.qayy.dto.KuncunListItem;
import cn.qayy.po.KdbNssLogPlans;
import cn.qayy.po.Plan;
import cn.qayy.po.Policy;
import cn.qayy.po.Register;
import cn.qayy.service.SynchronizationService;
/**
 * 初始化流向的工具类
 * 
 * @author jobs1127
 *
 */
public class InitPlansUtil {
	private static SimpleDateFormat dateFormaty = new SimpleDateFormat("yyyy");
	private static SimpleDateFormat dateFormatm = new SimpleDateFormat("MM");
	private static DecimalFormat DF1 = new DecimalFormat("0.0");// 1位小数
	/***
	 * 注册库初始流向
	 * @param registers 和流向相关的注册库
	 * @param p 流向
	 * @return 初始化后的流向
	 */
	public static Plan registerInit(List<Register> registers,Plan p) throws Exception{
		for (Register register : registers) {
			if(register.getCname().equals(p.getTerminal())) {
			 	p.setMgr(register.getMgr()); 
			 	//片区提成人
				p.setTichengbelong(p.getMgr());
			    p.setDaqu(register.getProvince());
			    p.setSpace(register.getSpace());
			    p.setCity(register.getCity());
			    p.setCounty(register.getCountry());
			    p.setZhenghe_qs(register.getZhengheqs());
			    p.setFenbu(register.getAddr());
			    p.setTerminaltype(register.getTerminaltype());
			    p.setTerminallev(register.getTerminallve());
			    p.setProvince(register.getShengfen());
			    return p;
			}
		}
		return null;
	}
	/***
	 * 流向的准备阶段的初始化，该阶段紧接着流向模板初始化的后面
	 * @param p
	 * @param request 请求
	 * @return
	 * @throws Exception
	 */
	public static Plan preparInit(Plan p,HttpServletRequest request) throws Exception {
		String[] yearAndMouths = p.getSdate().split("/");
		p.setYear(yearAndMouths[0]);
		p.setMouth(yearAndMouths[1]);
		p.setDataer(request.getSession().getAttribute("username").toString());
		p.setMtime(new Date());//更新时间
		//录入时间
		if(p.getId() == null) {
			p.setToday(DateUtils.dateToString(new Date(), "yyyy/MM/dd HH:mm:ss"));
		}
		
		//行为是另付时，直接把协议状态弄成5状态，表示另付的协议默认为合格协议
		if(p.getJudge().contains("另付")) {
			p.setPolicystatus("5");
		} 
		/**
		 * 销售行为是期初，并且流向备注包含毕期初，则毕掉该流向，用于标识该流向已被流向岗核查过库存
		 */
		if (p.getJudge().equals("期初")&&p.getDemo().contains("毕期初")) {
			p.setStatus1("毕期初"+DateUtils.dateToString(new Date(),"yyyy/MM/dd"));
		}
		return p;
	}
	/***
	 * 流向的其他属性的初始化，跟流向的客户、数量、行为、模式、真假自然流向标识 有关系
	 * @param p
	 * @param request 请求
	 * @return
	 * @throws Exception
	 */
	public static Plan otherInit(Plan p,HttpServletRequest request) throws Exception {
		/***
		 * 非自然流向为负数的纯销，直接赋值为待
		 */
		if(Float.parseFloat(p.getCount())<0
				&&p.getJudge().contains("纯销")
				&&!p.getClient().contains("QA")){
			p.setStatus1("待");
		}
		String product = p.getProduct(); 
		String pack = p.getPack();
		p.setCost(initProductCost(product, pack));
		return p;
	}
	
	/***
	 * 根据条线 品种、包装、数量计算生产折量
	 * @param tx
	 * @param product
	 * @param pack
	 * @param count
	 * @return
	 */
	private static String getScount(String tx,String product,String pack,String count){
		KdbNssLogPlans lp = new KdbNssLogPlans();
		lp.setScount("0");
		//生产折量
		if(tx!=null){
			if(tx.contains("Rx")){
				if(product.contains("A")){
					if (pack.equals("24")) {
						lp.setXsScount(DF1.format(Float.parseFloat(count)));
						lp.setScount(DF1.format(Float.parseFloat(count)));
					} else if (pack.equals("12") ) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(sc * 0.5));
						lp.setScount(DF1.format(sc * 0.5));
					} else if (pack.equals("36")) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(sc * 1.5));
						lp.setScount(DF1.format(sc * 1.5));
					} else if (pack.equals("48")) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(sc * 2));
						lp.setScount(DF1.format(sc * 2));
					} else if (pack.equals("20")) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(sc * 0.8333));
						lp.setScount(DF1.format(sc * 0.8333));
					} else if (pack.equals("30")) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(sc * 1.25));
						lp.setScount(DF1.format(sc * 1.25));
					} else if (pack.equals("40")) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(sc * 1.6666));
						lp.setScount(DF1.format(sc * 1.6666));
					} else if(pack.equals("240")) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(sc * 5));
						lp.setScount(DF1.format(sc * 5));
					} 
				}else if(product.contains("Y")){
					if (pack.equals("24")) {
						lp.setXsScount(DF1.format(Float.parseFloat(count)));
						lp.setScount(DF1.format(Float.parseFloat(count)));
					} else if (pack.equals("36")) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(sc * 1.5));
						lp.setScount(DF1.format(sc * 1.5));
					} else if (pack.equals("20")) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(sc * 0.8333));
						lp.setScount(DF1.format(sc * 0.8333));
					} else if (pack.equals("30")) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(sc * 1.25));
						lp.setScount(DF1.format(sc * 1.25));
					} else if (pack.equals("40")) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(sc * 1.6666));
						lp.setScount(DF1.format(sc * 1.6666));
					} else if (pack.equals("60")) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(sc * 2.5));
						lp.setScount(DF1.format(sc * 2.5));
					} else if (pack.equals("48")) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(sc * 2));
						lp.setScount(DF1.format(sc * 2));
					} 
				} else if(product.contains("Z")){
					if(pack.equals("48")){
						lp.setXsScount(DF1.format(Float.parseFloat(count)));
						lp.setScount(DF1.format(Float.parseFloat(count)));
					}else if(pack.equals("24")){
						float sc = (new Float(count));
						lp.setXsScount(DF1.format((sc * 0.5)));
						lp.setScount(DF1.format((sc * 0.5)));
					} else if(pack.equals("20")){
						float sc = (new Float(count));
						lp.setXsScount(DF1.format((sc * 0.4166)));
						lp.setScount(DF1.format((sc * 0.4166)));
					} else if(pack.equals("30")){
						float sc = (new Float(count));
						lp.setXsScount(DF1.format((sc * 0.625)));
						lp.setScount(DF1.format((sc * 0.625)));
					} else if(pack.equals("40")){
						float sc = (new Float(count));
						lp.setXsScount(DF1.format((sc * 0.8333)));
						lp.setScount(DF1.format((sc * 0.8333)));
					} else if(pack.equals("36")){
						float sc = (new Float(count));
						lp.setXsScount(DF1.format((sc * 0.75)));
						lp.setScount(DF1.format((sc * 0.75)));
					} else if(pack.equals("60")){
						float sc = (new Float(count));
						lp.setXsScount(DF1.format((sc * 1.25)));
						lp.setScount(DF1.format((sc * 1.25)));
					}
				}
			} else if(tx.contains("OTC")){
				if(product.contains("A")){
					if (pack.equals("30")) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(Float.parseFloat(count)));
						lp.setScount(DF1.format(sc * 1.5));
					} else if (pack.equals("12") ) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(sc * 0.4));
						lp.setScount(DF1.format(sc * 0.6));
					} else if (pack.equals("36")) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(sc * 1.2));
						lp.setScount(DF1.format(sc * 1.8));
					} else if (pack.equals("48")) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(sc * 1.6));
						lp.setScount(DF1.format(sc * 2.4));
					} else if (pack.equals("20")) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(sc * 0.6666));
						lp.setScount(DF1.format(sc * 1));
					} else if (pack.equals("24")) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(sc * 0.8));
						lp.setScount(DF1.format(sc * 1.2));
					} else if (pack.equals("40")) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(sc * 1.3333));
						lp.setScount(DF1.format(sc * 2));
					} else if(pack.equals("240")) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(sc * 5));
						lp.setScount(DF1.format(sc * 12));
					}
				} else if(product.contains("Y")){
					if (pack.equals("60")) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(Float.parseFloat(count)));
						lp.setScount(DF1.format(sc * 3));
					} else if (pack.equals("36")) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(sc * 0.6));
						lp.setScount(DF1.format(sc * 1.8));
					} else if (pack.equals("20")) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(sc * 0.3333));
						lp.setScount(DF1.format(sc * 1));
					} else if (pack.equals("30")) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(sc * 0.5));
						lp.setScount(DF1.format(sc * 1.5));
					} else if (pack.equals("40")) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(sc * 0.6666));
						lp.setScount(DF1.format(sc * 2));
					} else if (pack.equals("24")) {
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(sc * 0.4));
						lp.setScount(DF1.format(sc * 1.2));
					} else if (pack.equals("48")) { 
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(sc * 0.8));
						lp.setScount(DF1.format(sc * 2.4));
					} 
				} else if(product.contains("Z")){
					if(pack.equals("60")){
						float sc = (new Float(count));
						lp.setXsScount(DF1.format(Float.parseFloat(count)));
						lp.setScount(DF1.format(sc * 3));
					}else if(pack.equals("24")){
						float sc = (new Float(count));
						lp.setXsScount(DF1.format((sc * 0.4)));
						lp.setScount(DF1.format(sc * 1.2));
					} else if(pack.equals("20")){
						float sc = (new Float(count));
						lp.setXsScount(DF1.format((sc * 0.3333)));
						lp.setScount(DF1.format(sc * 1));
					} else if(pack.equals("30")){
						float sc = (new Float(count));
						lp.setXsScount(DF1.format((sc * 0.5)));
						lp.setScount(DF1.format(sc * 1.5));
					} else if(pack.equals("40")){
						float sc = (new Float(count));
						lp.setXsScount(DF1.format((sc * 0.6666)));
						lp.setScount(DF1.format(sc * 2));
					} else if(pack.equals("36")){
						float sc = (new Float(count));
						lp.setXsScount(DF1.format((sc * 0.6)));
						lp.setScount(DF1.format(sc * 1.8));
					} else if(pack.equals("48")){
						float sc = (new Float(count));
						lp.setXsScount(DF1.format((sc * 0.8)));
						lp.setScount(DF1.format(sc * 2.4));
					}
				}
			}
		}
		return lp.getScount();
	}
	
	/***
	 * 初始化流向的销售折量/生产折量
	 * Rx条线，销售折量=生产折量
	 * OTC条线：生产折量：A20=Y20=Z20=1
	 * @param p
	 * @return
	 * @throws Exception
	 * 1、初始化流向时
	 * 2、同步更新时
	 * 3、半夜自动更新时
	 */
	public static Plan salesInit(Plan p) throws Exception {
		String product = p.getProduct(); 
		String pack = p.getPack();
		String count = p.getCount();
		float sc = (new Float(count));
		if("B".equals(product)) {
			//其他省份
			if(p.getProvince()!=null && !p.getProvince().contains("新疆")) {
				if("5".equals(pack)) {
					p.setXsScount(DF1.format(sc * 1));
					p.setScount(DF1.format(sc * 1));
				}
				if("10".equals(pack)) {
					p.setXsScount(DF1.format(sc * 2));
					p.setScount(DF1.format(sc * 2));
				}
			} 
			
			//新疆
			if(p.getProvince()!=null && p.getProvince().contains("新疆")) {
				if(p.getMode()!=null && p.getMode().contains("自营")) {
					if("5".equals(pack)) {
						p.setXsScount(DF1.format(sc * 1));
					}
					if("10".equals(pack)) {
						p.setXsScount(DF1.format(sc * 2));
					}
				}
				if(p.getMode()!=null && p.getMode().contains("小包")) {
					if("5".equals(pack)) {
						p.setXsScount(DF1.format(sc * 1));
					}
					if("10".equals(pack)) {
						p.setXsScount(DF1.format(sc * 1));
					}
				}
				if(p.getMode()!=null && p.getMode().contains("预付")) {
					if("5".equals(pack)) {
						p.setXsScount(DF1.format(sc * 0.5));
					}
					if("10".equals(pack)) {
						p.setXsScount(DF1.format(sc * 1));
					}
				}
			} 
		}
		if(p.getXieyizhuangtai().contains("Rx")){
			if(product.equals("A")){
				if (pack.equals("24")) {
					p.setXsScount(DF1.format(sc));
					p.setScount(DF1.format(sc));
				} else if (pack.equals("12") ) {
					p.setXsScount(DF1.format(sc * 0.5));
					p.setScount(DF1.format(sc * 0.5));
				} else if (pack.equals("36")) {
					p.setXsScount(DF1.format(sc * 1.5));
					p.setScount(DF1.format(sc * 1.5));
				} else if (pack.equals("48")) {
					p.setXsScount(DF1.format(sc * 2));
					p.setScount(DF1.format(sc * 2));
				} else if (pack.equals("20")) {
					p.setXsScount(DF1.format(sc * 0.8333));
					p.setScount(DF1.format(sc * 0.8333));
				} else if (pack.equals("30")) {
					p.setXsScount(DF1.format(sc * 1.25));
					p.setScount(DF1.format(sc * 1.25));
				} else if (pack.equals("40")) {
					p.setXsScount(DF1.format(sc * 1.6666));
					p.setScount(DF1.format(sc * 1.6666));
				} else if(pack.equals("240")) {
					p.setXsScount(DF1.format(sc * 10));
					p.setScount(DF1.format(sc * 10));
				} else if(pack.equals("480")) {
					p.setXsScount(DF1.format(sc * 20));
					p.setScount(DF1.format(sc * 20));
				} 
			}else if(product.equals("Y")){
				if (pack.equals("24")) {
					p.setXsScount(DF1.format(sc));
					p.setScount(DF1.format(sc));
				} else if (pack.equals("36")) {
					p.setXsScount(DF1.format(sc * 1.5));
					p.setScount(DF1.format(sc * 1.5));
				} else if (pack.equals("20")) {
					p.setXsScount(DF1.format(sc * 0.8333));
					p.setScount(DF1.format(sc * 0.8333));
				} else if (pack.equals("30")) {
					p.setXsScount(DF1.format(sc * 1.25));
					p.setScount(DF1.format(sc * 1.25));
				} else if (pack.equals("40")) {
					p.setXsScount(DF1.format(sc * 1.6666));
					p.setScount(DF1.format(sc * 1.6666));
				} else if (pack.equals("60")) {
					p.setXsScount(DF1.format(sc * 2.5));
					p.setScount(DF1.format(sc * 2.5));
				} else if (pack.equals("48")) {
					p.setXsScount(DF1.format(sc * 2));
					p.setScount(DF1.format(sc * 2));
				} 
			} else if(product.contains("Z")){
				if(pack.equals("48")){
					p.setXsScount(DF1.format(sc));
					p.setScount(DF1.format(sc));
				}else if(pack.equals("24")){
					p.setXsScount(DF1.format((sc * 0.5)));
					p.setScount(DF1.format((sc * 0.5)));
				} else if(pack.equals("20")){
					p.setXsScount(DF1.format((sc * 0.4166)));
					p.setScount(DF1.format((sc * 0.4166)));
				} else if(pack.equals("30")){
					p.setXsScount(DF1.format((sc * 0.625)));
					p.setScount(DF1.format((sc * 0.625)));
				} else if(pack.equals("40")){
					p.setXsScount(DF1.format((sc * 0.8333)));
					p.setScount(DF1.format((sc * 0.8333)));
				} else if(pack.equals("36")){
					p.setXsScount(DF1.format((sc * 0.75)));
					p.setScount(DF1.format((sc * 0.75)));
				} else if(pack.equals("60")){
					p.setXsScount(DF1.format((sc * 1.25)));
					p.setScount(DF1.format((sc * 1.25)));
				}
			}
		} else if(p.getXieyizhuangtai().contains("OTC")){
			if(product.contains("A")){
				if (pack.equals("30")) {
					p.setXsScount(DF1.format(sc));
					p.setScount(DF1.format((sc * 1.5)));
				} else if (pack.equals("12") ) {
					p.setXsScount(DF1.format(sc * 0.4));
					p.setScount(DF1.format((sc * 0.6)));
				} else if (pack.equals("36")) {
					p.setXsScount(DF1.format(sc * 1.2));
					p.setScount(DF1.format((sc * 1.8)));
				} else if (pack.equals("48")) {
					p.setXsScount(DF1.format(sc * 1.6));
					p.setScount(DF1.format((sc * 2.4)));
				} else if (pack.equals("20")) {
					p.setXsScount(DF1.format(sc * 0.6666));
					p.setScount(DF1.format((sc * 1)));
				} else if (pack.equals("24")) {
					p.setXsScount(DF1.format(sc * 0.8));
					p.setScount(DF1.format((sc * 1.2)));
				} else if (pack.equals("40")) {
					p.setXsScount(DF1.format(sc * 1.3333));
					p.setScount(DF1.format((sc * 2)));
				} else if(pack.equals("240")) {
					p.setXsScount(DF1.format(sc * 10));
					p.setScount(DF1.format((sc * 10)));
				} else if(pack.equals("480")) {
					p.setXsScount(DF1.format(sc * 20));
					p.setScount(DF1.format((sc * 20)));
				} 
			} else if(product.contains("Y")){
				if (pack.equals("60")) {
					p.setXsScount(DF1.format(sc));
					p.setScount(DF1.format((sc * 3)));
				} else if (pack.equals("36")) {
					p.setXsScount(DF1.format(sc * 0.6));
					p.setScount(DF1.format((sc * 1.8)));
				} else if (pack.equals("20")) {
					p.setXsScount(DF1.format(sc * 0.3333));
					p.setScount(DF1.format((sc * 1)));
				} else if (pack.equals("30")) {
					p.setXsScount(DF1.format(sc * 0.5));
					p.setScount(DF1.format((sc * 1.5)));
				} else if (pack.equals("40")) {
					p.setXsScount(DF1.format(sc * 0.6666));
					p.setScount(DF1.format((sc * 2)));
				} else if (pack.equals("24")) {
					p.setXsScount(DF1.format(sc * 0.4));
					p.setScount(DF1.format((sc * 1.2)));
				} else if (pack.equals("48")) {
					p.setXsScount(DF1.format(sc * 0.8));
					p.setScount(DF1.format((sc * 2.4)));
				} 
			} else if(product.contains("Z")){
				if(pack.equals("60")){
					p.setXsScount(DF1.format(sc));
					p.setScount(DF1.format((sc * 3)));
				}else if(pack.equals("24")){
					p.setXsScount(DF1.format((sc * 0.4)));
					p.setScount(DF1.format((sc * 1.2)));
				} else if(pack.equals("20")){
					p.setXsScount(DF1.format((sc * 0.3333)));
					p.setScount(DF1.format((sc * 1)));
				} else if(pack.equals("30")){
					p.setXsScount(DF1.format((sc * 0.5)));
					p.setScount(DF1.format((sc * 1.5)));
				} else if(pack.equals("40")){
					p.setXsScount(DF1.format((sc * 0.6666)));
					p.setScount(DF1.format((sc * 2)));
				} else if(pack.equals("36")){
					p.setXsScount(DF1.format((sc * 0.6)));
					p.setScount(DF1.format((sc * 1.8)));
				} else if(pack.equals("48")){
					p.setXsScount(DF1.format((sc * 0.8)));
					p.setScount(DF1.format((sc * 2.4)));
				}
			}
		}
		return p;
	}
	
	/***
	 * 协议初始化流向,操作流向时，去匹配协议
	 * @param policys
	 * @param p
	 */
	public static Plan policyInit(List<Policy> policys,List<Policy> xs_policys, Plan p) throws Exception{
		String product = p.getProduct();
		String pack = p.getPack();
		String client = p.getClient();
		String yifan = p.getTerminal();
		String date = p.getSdate();
		Policy logP = null;
		
		if(p.getJudge().contains("纯销")) {
			for (Policy po : policys) {
				if(product.equals(po.getProduct()) 
						&& pack.equals(po.getPage())
						&& yifan.equals(po.getQsterminal())) {
					// 协议开始时间<=流向时间<协议结束时间
					if(DateUtils.isDateGt2Eq(date,po.getXieyistarttime())
							&&DateUtils.isDateLt(date,po.getXieyiendtime())) {
						logP = po;
						break;
					}
				}
			}
		} else if(p.getJudge().contains("销售")) {
			//批量导入协议或新增、修改协议时，不存在纯销协议或销售协议的说法，故传值null过来，这时需要用policys去匹配销售流向。
			if(xs_policys == null) {
				xs_policys = policys;
			}
			//优先匹配T3政策
			for(Policy po:xs_policys) {
				if(product.equals(po.getProduct()) 
						&& pack.equals(po.getPage())
						&& client.equals(po.getClient())
						&& po.getTerminaltype().contains("T3")
						&& po.getMode().contains("预付")) {
					// 协议开始时间<=流向时间<协议结束时间
					if(DateUtils.isDateGt2Eq(date,po.getXieyistarttime())
							&&DateUtils.isDateLt(date,po.getXieyiendtime())) {
						logP = po;
						break;
					}
				}
			}
			//如果没匹配到T3政策，则尝试匹配其他政策
			if(logP == null) {
				for(Policy po:xs_policys) {
					if(product.equals(po.getProduct()) 
							&& pack.equals(po.getPage())
							&& client.equals(po.getClient())
							&& po.getMode().contains("预付")) {
						// 协议开始时间<=流向时间<协议结束时间
						if(DateUtils.isDateGt2Eq(date,po.getXieyistarttime())
								&&DateUtils.isDateLt(date,po.getXieyiendtime())) {
							logP = po;
							break;
						}
					}
				}
			}
		}
		policy_into_logs(p,logP);
		return p;
	}
	/***
	 * 根据协议id匹配流向
	 * @param Plan 流向
	 * @param Policy 协议
	 */
	public static Plan policyInitByPid(Plan p,Policy logP) throws Exception{
		policy_into_logs(p,logP);
		return p;
	}
	/***
	 * 协议初始化流向,操作协议时，对流向进行更新
	 * 
	 * 时间关系：协议开始时间<=流向时间<协议结束时间
	 * @param policys
	 * @param p
	 */
	public static Plan policyInitPlans(List<Policy> policys,List<Policy> xs_policys, Plan p) throws Exception{
		String product = p.getProduct();
		String pack = p.getPack();
		String client = p.getClient();
		String yifan = p.getTerminal();
		String date = p.getSdate();
		Policy logP = null;
		
		if(p.getJudge().contains("纯销")) {
			for (Policy po : policys) {
				if(product.equals(po.getProduct()) 
						&& pack.equals(po.getPage())
						&& yifan.equals(po.getQsterminal())) {
					// 协议开始时间<=流向时间<协议结束时间
					if(DateUtils.isDateGt2Eq(date,po.getXieyistarttime())
							&&DateUtils.isDateLt(date,po.getXieyiendtime())) {
						logP = po;
						break;
					}
				}
			}
		} else if(p.getJudge().contains("销售")) {
			//批量导入协议或新增、修改协议时，不存在纯销协议或销售协议的说法，故传值null过来，这时需要用policys去匹配销售流向。
			if(xs_policys == null) {
				xs_policys = policys;
			}
			//优先匹配T3政策
			for(Policy po:xs_policys) {
				if(product.equals(po.getProduct()) 
						&& pack.equals(po.getPage())
						&& client.equals(po.getClient())
						&& po.getTerminaltype().contains("T3")
						&& po.getMode().contains("预付")) {
					// 协议开始时间<=流向时间<协议结束时间
					if(DateUtils.isDateGt2Eq(date,po.getXieyistarttime())
							&&DateUtils.isDateLt(date,po.getXieyiendtime())) {
						logP = po;
						break;
					}
				}
			}
			//如果没匹配到T3政策，则尝试匹配其他政策
			if(logP == null) {
				for(Policy po:xs_policys) {
					if(product.equals(po.getProduct()) 
							&& pack.equals(po.getPage())
							&& client.equals(po.getClient())
							&& po.getMode().contains("预付")) {
						// 协议开始时间<=流向时间<协议结束时间
						if(DateUtils.isDateGt2Eq(date,po.getXieyistarttime())
								&&DateUtils.isDateLt(date,po.getXieyiendtime())) {
							logP = po;
							break;
						}
					}
				}
			}
		}
		policys_update_plans(p,logP);
		return p;
	}
	/***
	 * 协议初始化流向
	 * @param policys 多个协议
	 * @param plans 多个流向
	 */
	public static void policysInitPlan(List<Policy> policys,List<Policy> xs_policys,List<Plan> plans) throws Exception{
		for (Plan p : plans) {
			policyInitPlans(policys,xs_policys,p);
		}
	}
	
	/***
	 * 协议初始化流向,一个协议，一个流向，流向匹配协议最终要走的方法,操作流向时，调用的方法
	 * @param lp
	 * @param logP
	 * @throws Exception
	 */
	public static void policy_into_logs(Plan lp,Policy logP) throws Exception{
		//如果协议不空
		if (logP!=null) {
			lp.setZhongbiaojiamoney(ArithUtil.money(logP.getZhongbiaojia(),lp.getCount()));//中标金额
			lp.setPeisonglv(ArithUtil.percent(logP.getKaipiaojia(),logP.getZhongbiaojia()));//配送率
			lp.setKaipiaojiamoney(ArithUtil.money(logP.getKaipiaojia(),lp.getCount()));//开票金额
			//1服务费
			lp.setBasic1(logP.getTuiguangmoney());
			lp.setMoney1(ArithUtil.money(logP.getTuiguangmoney(),lp.getCount()));
			//3服务费
			lp.setPiaoju3(logP.getFapiaomoney());
			lp.setMoney3(ArithUtil.money(logP.getFapiaomoney(),lp.getCount()));
			//4服务费
			lp.setDabiao4(logP.getDaibiaomoney());
			lp.setMoney4(ArithUtil.money(logP.getDaibiaomoney(),lp.getCount()));
			
			//账单
			lp.setZhangdan1(getJsZhangdan(lp, logP));
			lp.setDaibiao(logP.getDaibiao());// 代表 
			lp.setShoukuangren(logP.getShoukuangren());//收款人
			lp.setKaihuhang(logP.getKaihuhang());//开户行
			lp.setZhanghao(logP.getZhanghao());//账号
			lp.setKaipiaofangshi(logP.getKaipiaofangshi());//票据方案
			lp.setTotalmoney(ArithUtil.total(lp.getMoney1(),lp.getMoney3(),lp.getMoney4()));//总费用
			lp.setAtsum(logP.getDijia());//协议测算价
			lp.setYingyumoney(logP.getBiaozhuncsdj());//标准测算价
			lp.setYinyukaiguan(logP.getKaipiaojia());//开票价
			lp.setCuxiao_ed_money(logP.getZhongbiaojia());//中标价
			lp.setJsmode(logP.getJsmode());// 结算方式
			//中标费用率
			lp.setFeiyonglv(ArithUtil.percent(lp.getTotalmoney(), lp.getZhongbiaojiamoney()));
			lp.setClientpolicyId(logP.getId() + "");// 协议id
			lp.setPolicystatus(logP.getGuihuanriqi());//协议状态
			
			if(logP.getZhanghao()!=null && logP.getZhanghao().contains(Constant.BANK_CARD)) {
				lp.setYhzhanghao(StringUtil.formatStringGetNumber(logP.getZhanghao()));	
			}
			//模式、渠道、条线、省份 流向岗均可以录入，但是一旦有了协议，则参考协议的，必须保证和协议的一致。
			lp.setMode(logP.getMode());// 模式
			lp.setTerminaltype(logP.getTerminaltype());//渠道
			lp.setXieyizhuangtai(logP.getQudaolie());//条线
			lp.setClient(logP.getClient());//客户
			lp.setProvince(logP.getProvince());//省份
		} else {// 没有找到对应的协议的处理，处理为自然流向
			lp.setKaipiaofangshi("");//票据方案
			lp.setShoukuangren("");//收款人
			lp.setKaihuhang("");//开户行
			lp.setZhanghao("");//账号
			// 推广1、财务3、达标4、转移2、账单
			lp.setBasic1("0");
			lp.setMoney1("0");
			lp.setPiaoju3("0");
			lp.setMoney3("0");
			lp.setDabiao4("0");
			lp.setMoney4("0");
			lp.setZhongbiaojiamoney("0");// 中标金额
			lp.setPeisonglv("0%");// 配送率
			lp.setKaipiaojiamoney("0");// 开票金额
			lp.setYingyumoney("0");//标准测算价
			lp.setAtsum("0");//协议测算价
			lp.setJsmode("");// 结算方式
			lp.setZhangdan1("");
			lp.setClientpolicyId("0");// 协议id
			lp.setStatus7("");//是否手动匹配过，自然流向，清掉其标识
			lp.setPolicystatus("0");//协议状态为0
			lp.setTotalmoney("0");// 总费用
			lp.setYhzhanghao("");//银行账号
			lp.setYinyukaiguan("0");//开票价
			lp.setCuxiao_ed_money("0");//中标价
			
			lp.setStatus1("押");// 推广费状态
			lp.setStatus3("押");// 财务费状态
			lp.setStatus4("押");// 达标返利状态
			
			lp.setDaibiao("");// 代表 
			lp.setMoneybill1("");//流向的提单日期
			lp.setFeiyonglv("0");// 中标费用率
			lp.setTidanfangshi("");//提单方式
			/**没有协议时，参考流向岗录入的**/
			//lp.setClient("QA");// 客户 
			//lp.setMode("");// 模式
			//lp.setTerminaltype("");//渠道
			//lp.setXieyizhuangtai("");//条线
		}
		
		if (logP!=null) {
			//5开发奖励
			lp.setKaifa5(logP.getKaifajianlishixiang());
			lp.setMoney5(ArithUtil.money(logP.getKaifajianlishixiang(),lp.getCount()));
		} else {
			lp.setKaifa5("0");
			lp.setMoney5("0");
			lp.setStatus5("押");// 开发奖励
		}
		if (logP!=null) {
			//业务员开发奖励,录入协议时，需要 录入人员等比折算
			lp.setKaifaMgr(logP.getKaifaMgr());
			lp.setMoneyMgr(ArithUtil.money(logP.getKaifaMgr(),lp.getCount()));
		} else {
			lp.setKaifaMgr("0");
			lp.setMoneyMgr("0");
			lp.setStatusMgr("押");//经理开发奖励
		}
	}
	
	/***
	 * 协议初始化流向,一个协议，一个流向，操作协议时，去更新流向
	 * @param lp
	 * @param logP
	 * @throws Exception
	 */
	public static void policys_update_plans(Plan lp,Policy logP) throws Exception{
		//如果协议不空
		if (logP!=null) {
			lp.setZhongbiaojiamoney(ArithUtil.money(logP.getZhongbiaojia(),lp.getCount()));//中标金额
			lp.setPeisonglv(ArithUtil.percent(logP.getKaipiaojia(),logP.getZhongbiaojia()));//配送率
			lp.setKaipiaojiamoney(ArithUtil.money(logP.getKaipiaojia(),lp.getCount()));//开票金额
			//1服务费
			lp.setBasic1(logP.getTuiguangmoney());
			lp.setMoney1(ArithUtil.money(logP.getTuiguangmoney(),lp.getCount()));
			//3服务费
			lp.setPiaoju3(logP.getFapiaomoney());
			lp.setMoney3(ArithUtil.money(logP.getFapiaomoney(),lp.getCount()));
			//4服务费
			lp.setDabiao4(logP.getDaibiaomoney());
			lp.setMoney4(ArithUtil.money(logP.getDaibiaomoney(),lp.getCount()));
			
			//账单
			lp.setZhangdan1(getJsZhangdan(lp, logP));
			lp.setDaibiao(logP.getDaibiao());// 代表 
			lp.setShoukuangren(logP.getShoukuangren());//收款人
			lp.setKaihuhang(logP.getKaihuhang());//开户行
			lp.setZhanghao(logP.getZhanghao());//账号
			lp.setKaipiaofangshi(logP.getKaipiaofangshi());//票据方案
			lp.setTotalmoney(ArithUtil.total(lp.getMoney1(),lp.getMoney3(),lp.getMoney4()));//总费用
			lp.setAtsum(logP.getDijia());//协议测算价
			lp.setYingyumoney(logP.getBiaozhuncsdj());//标准测算价
			lp.setYinyukaiguan(logP.getKaipiaojia());//开票价
			lp.setCuxiao_ed_money(logP.getZhongbiaojia());//中标价
			lp.setJsmode(logP.getJsmode());// 结算方式
			//中标费用率
			lp.setFeiyonglv(ArithUtil.percent(lp.getTotalmoney(), lp.getZhongbiaojiamoney()));
			lp.setClientpolicyId(logP.getId() + "");// 协议id
			lp.setPolicystatus(logP.getGuihuanriqi());//协议状态
			
			if(logP.getZhanghao()!=null && logP.getZhanghao().contains(Constant.BANK_CARD)) {
				lp.setYhzhanghao(StringUtil.formatStringGetNumber(logP.getZhanghao()));	
			}
			//模式、渠道、条线、省份 流向岗均可以录入，但是一旦有了协议，则参考协议的，必须保证和协议的一致。
			lp.setMode(logP.getMode());// 模式
			lp.setTerminaltype(logP.getTerminaltype());//渠道
			lp.setXieyizhuangtai(logP.getQudaolie());//条线
			lp.setClient(logP.getClient());//客户
			lp.setProvince(logP.getProvince());//省份
			
			//5开发奖励
			lp.setKaifa5(logP.getKaifajianlishixiang());
			lp.setMoney5(ArithUtil.money(logP.getKaifajianlishixiang(),lp.getCount()));
			
			//业务员开发奖励 
			lp.setKaifaMgr(logP.getKaifaMgr());
			lp.setMoneyMgr(ArithUtil.money(logP.getKaifaMgr(),lp.getCount()));
		} 
	}
	
	
	/**
	 * 获取结算账单
	 * @param plan
	 * @param p
	 * @return
	 */
	public static String getJsZhangdan(Plan plan,Policy p) {
		String zhangdan = "";
		if(p == null) {
			return zhangdan;
		}
		if (p.getJsmode().contains("次月结")) {
			String currentyear = plan.getYear();
			String currentmouth = plan.getMouth();
			String year = "";
			String mouth = "";
			if (currentmouth.equals("12")) {
				year = "Y" + (StringUtil.parseInt(currentyear) + 1);
				mouth = "M01";
			} else {
				year = "Y" + currentyear;
				if (StringUtil.parseInt(currentmouth) < 9) {
					mouth = "M0" + (StringUtil.parseInt(currentmouth) + 1);
				} else {
					mouth = "M" + (StringUtil.parseInt(currentmouth) + 1);
				}
			}
			zhangdan = year + mouth;
		}
		if (p.getJsmode().contains("押1月结")) {
			String currentyear = plan.getYear();
			String currentmouth = plan.getMouth();
			String year = "";
			String mouth = "";
			if (currentmouth.equals("12")) {
				year = "Y" + (StringUtil.parseInt(currentyear) + 1);
				mouth = "M02";
			} else if (currentmouth.contains("11")) {
				year = "Y" + (StringUtil.parseInt(currentyear) + 1);
				mouth = "M01";
			} else {
				year = "Y" + currentyear;
				if (new Integer(currentmouth) < 8) {
					mouth = "M0" + (StringUtil.parseInt(currentmouth) + 2);
				} else {
					mouth = "M" + (StringUtil.parseInt(currentmouth) + 2);
				}
			}
			zhangdan = year + mouth;
		}
		if (p.getJsmode().contains("押2月结")) {
			String currentyear = plan.getYear();
			String currentmouth = plan.getMouth();
			String year = "";
			String mouth = "";
			if (currentmouth.equals("12")) {
				year = "Y" + (StringUtil.parseInt(currentyear) + 1);
				mouth = "M03";
			} else if (currentmouth.contains("11")) {
				year = "Y" + (StringUtil.parseInt(currentyear) + 1);
				mouth = "M02";
			} else if (currentmouth.contains("10")) {
				year = "Y" + (StringUtil.parseInt(currentyear) + 1);
				mouth = "M01";
			} else {
				year = "Y" + currentyear;
				if (new Integer(currentmouth) < 7) {
					mouth = "M0" + (StringUtil.parseInt(currentmouth) + 3);
				} else {
					mouth = "M" + (StringUtil.parseInt(currentmouth) + 3);
				}
			}
			zhangdan = year + mouth;
		}
		return zhangdan;
	}
	
	/***
	 * 自动匹配客户 若对应多个客户返回多个客户，否则返回null
	 * @param p 流向
	 * @param policys 协议s
	 * @throws Exception
	 */
	public static List<String> autoFindClient(List<Policy> policys, Plan p) throws Exception{
		String client = p.getClient();
		String product = p.getProduct();
		String pack = p.getPack();
		String yifan = p.getTerminal();
		String date = p.getSdate();
		List<String> clients = new ArrayList<String>(Constant.INIT_CAPACITY);
		//若用户未填写客户，则系统帮忙初始化客户
		if(!StringUtil.isNotBlank(client)) {
			for(Policy po:policys) {
				if(product.equals(po.getProduct()) 
						&& pack.equals(po.getPage())
						&& yifan.equals(po.getQsterminal())) {
					// 协议开始时间<=流向时间<协议结束时间
					if(DateUtils.isDateGt2Eq(date,po.getXieyistarttime())
							&&DateUtils.isDateLt(date,po.getXieyiendtime())) {
						clients.add(po.getClient());
					}
				}
			}
			if(clients.isEmpty()) {//未找到客户，初始化为QA
				client = "QA";
			} else if(clients.size()==1){//有且仅仅找到一个客户，则初始化客户
				client = clients.get(0);
			} else {//找到多个返回多个
				return clients;
			}
		}
		p.setClient(client);
		return null;
	}
	/***
	 * 初始化真自然流，跟流向的客户、品种、包装、入货乙方有关系
	 * @param keys
	 * @param p
	 * @return
	 * @throws Exception
	 */
	public static Plan realNaturalFlowKeys(Set<String> keys, Plan p) throws Exception{
		if(!Constant.noRealNaturalFlow.equals(p.getStatus6())) {
			//用户明确输入了真自然流
			if(Constant.realNaturalFlow.equals(p.getStatus6())) {
				p.setStatus6(Constant.realNaturalFlow);
			} else {//用户没有输入的情况，自动匹配
				String key = p.getClient()+"-"+p.getTerminal()+"-"+p.getProduct()+"-"+p.getPack();
				if(keys != null && keys.contains(key)) {
					p.setStatus6(Constant.realNaturalFlow);
				}
			}
		}
		return p;
	}
	
	/***
	 * 下载时间理论库存
	 * @param resultItems
	 */
	public static void downLoadKuCun(List<KuncunListItem> resultItems){
		ExcelUtils eu = ExcelUtils.getInstance();
		String[] rowTitle = {"商业", "省份", "条线","模式", "客户","品种", "包装", "期初", "销售",
				"调进","调出", "纯销", "理论库存", "截止时间","期初折量", "销售折量", "调进折量", "调出折量",
				"纯销折量", "库存折量"};
		List<Object[]> listExport = new ArrayList<Object[]>();
		for(KuncunListItem item:resultItems){
			Object[] obj = new Object[20];
			obj[0] = item.getCompany()==null?"":item.getCompany();
			obj[1] = item.getProvince()==null?"":item.getProvince();
			obj[2] = item.getTx()==null?"":item.getTx();
			obj[3] = item.getPmode()==null?"":item.getPmode();
			obj[4] = item.getClient()==null?"":item.getClient();
			obj[5] = item.getProduct()==null?"":item.getProduct();
			obj[6] = item.getPack()==null?"":item.getPack();
			obj[7] = item.getQichu()==null?"":item.getQichu();
			obj[8] = item.getXiaoshou()==null?"":item.getXiaoshou();
			obj[9] = item.getDiaojing()==null?"":item.getDiaojing();
			obj[10] = item.getDiaochu()==null?"":item.getDiaochu();
			obj[11] = item.getCunxiao()==null?"":item.getCunxiao();
			obj[12] = item.getKucun()==null?"":item.getKucun();
			obj[13] = item.getEtime()==null?"":item.getEtime();
			obj[14] = item.getQichuScount()==null?"":item.getQichuScount();
			obj[15] = item.getXiaoshouScount()==null?"":item.getXiaoshouScount();
			obj[16] = item.getDiaojingScount()==null?"":item.getDiaojingScount();
			obj[17] = item.getDiaochuScount()==null?"":item.getDiaochuScount();
			obj[18] = item.getCunxiaoScount()==null?"":item.getCunxiaoScount();
			obj[19] = item.getKucunScount()==null?"":item.getKucunScount();
			listExport.add(obj);
		}
		if(!listExport.isEmpty()){
			String realname = eu.exportCvsNoReflection(listExport, rowTitle);
			try {
				eu.downloadExcel(realname);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/***
	 * 计算时间理论库存
	 * @param year 当前年
	 * @param etime 截止时间
	 * @param map 存放了以商业公司为key,vlaue=省份
	 * @param mapID 存放了以商业公司为key,vlaue=是否是ID账号商业 标识
	 * @param listYifan 当前年 所有的乙方集合
	 * @param listJiafan 当前年 所有的甲方集合
	 * @return
	 * @throws Exception
	 */
	public static List<KuncunListItem> calculateKuCun(String year,String etime,Map<String,String> map,Map<String,String> mapID,List<Plan> listYifan,List<Plan> listJiafan) throws Exception{
		//获取所有需要参加计算的商业公司或客户，包括小包和预付的，考虑充当过乙方的公司，只充当了甲方没充当乙方为无效数据
		List<KuncunListItem> resultItems_last = new ArrayList<KuncunListItem>(Constant.SMALL_CAPACITY*8);
		List<KuCunItem> resultItems_mid = new ArrayList<KuCunItem>(Constant.SMALL_CAPACITY*8);
		List<KuncunListItem> resultItems_mid_xiaobao = new ArrayList<KuncunListItem>(Constant.SMALL_CAPACITY*8);
		List<KuncunListItem> resultItems = new ArrayList<KuncunListItem>(Constant.SMALL_CAPACITY*8);
		List<KuncunListItem> items = new ArrayList<KuncunListItem>(Constant.SMALL_CAPACITY*8);
		List<KuncunListItem> allItems = new ArrayList<KuncunListItem>(Constant.SMALL_CAPACITY*8);
		
		for(Plan plan:listYifan){
			String terminal = plan.getTerminal();
			String product = plan.getProduct();
			String pack = plan.getPack();
			String province = map.get(terminal);
			String complanID = mapID.get(terminal);
			String mode = plan.getMode();
			String client = plan.getClient();
			String judge = plan.getJudge();
			String count = plan.getCount();
			String scount = plan.getXsScount();
			String tx = plan.getXieyizhuangtai();
//			String tx = "Rx";
//			if(pack.equals("20") || pack.equals("30") || pack.equals("40")) {
//				tx = "OTC";
//			}
			KuncunListItem item = new KuncunListItem(terminal,product,pack,mode,tx,client);
			if(judge.equals("期初")){
				item.setQichu(count);
				item.setQichuScount(scount);
				item.setJudge("期初");
			}
			if(judge.equals("销售")){
				item.setXiaoshou(count);
				item.setXiaoshouScount(scount);
				item.setJudge("销售");
			}
			if(judge.equals("调拨")){
				item.setDiaojing(count);
				item.setDiaojingScount(scount);
				item.setJudge("调进");
			}
			item.setProvince(province);
			item.setCompanyID(complanID);
			
			//乙方存放明细项
			items.add(item);
			//所有不重复的item：公司+品种+包装+模式+客户+条线
			if(!allItems.contains(item)){
				allItems.add(item);
			}
		}
		//long end = System.currentTimeMillis();
		//System.out.println("查询乙方："+(end-start)/1000);
		//start=System.currentTimeMillis();
		for(Plan plan:listJiafan){
			String commercial1 = plan.getCommercial1();
			String product = plan.getProduct();
			String pack = plan.getPack();
			String province = map.get(commercial1);
			String complanID = mapID.get(commercial1);
			String mode = plan.getMode();
			String client = plan.getClient();
			String judge = plan.getJudge();
			String count = plan.getCount();
			String scount = plan.getXsScount();
			String tx = plan.getXieyizhuangtai();
//			String tx = "Rx";
//			if(pack.equals("20") || pack.equals("30") || pack.equals("40")) {
//				tx = "OTC";
//			}
			KuncunListItem item = new KuncunListItem(commercial1,product,pack,mode,tx,client);
			if(judge.equals("纯销")){
				item.setCunxiao(count);
				item.setCunxiaoScount(scount);
				item.setJudge("纯销");
			}
			if(judge.equals("调拨")){
				item.setDiaochu(count);
				item.setDiaochuScount(scount);
				item.setJudge("调出");
			}
			item.setProvince(province);
			item.setCompanyID(complanID);
			//甲方存放明细项 公司+品种+包装+模式+客户+条线
			items.add(item);
			if(!allItems.contains(item)){
				allItems.add(item);
			}
		}
		//System.out.println("items.size:"+items.size());
		//end=System.currentTimeMillis();
		//System.out.println("查询甲方："+(end-start)/1000);
		//start=System.currentTimeMillis();
		/***
		 * 循环迭代所有的不重复的库存项，对各个库存项的字段进行初始化
		 * 这些不重复的库存项决定了下载后库存数据的行数
		 */
		for(KuncunListItem all:allItems){
			Float qichu = 0f;
			Float xiaoshou = 0f;
			Float diaojing = 0f;
			Float cunxiao = 0f;
			Float diaochu = 0f;
			
			Float qichuS = 0f;
			Float xiaoshouS = 0f;
			Float diaojingS = 0f;
			Float cunxiaoS = 0f;
			Float diaochuS = 0f;
			for(KuncunListItem item:items){//所有库存项
				/***
				 * 非小包、非自营 都是按照公司+品种+包装+模式+客户 确定唯一项 
				 */
				if(all.getCompany().equals(item.getCompany())
						&&all.getProduct().equals(item.getProduct())
						&&all.getPack().equals(item.getPack())
						&&all.getClient().equals(item.getClient())
						&&all.getPmode().equals(item.getPmode())){
					//乙方
					if(item.getJudge().contains("期初")){
						try {
							qichu = Float.parseFloat(item.getQichu());
							qichuS = Float.parseFloat(item.getQichuScount());
						} catch (Exception e) {
							qichu = 0f;
							qichuS = 0f;
						}
					}
					if(item.getJudge().contains("销售")){
						try {
							xiaoshou = Float.parseFloat(item.getXiaoshou());
							xiaoshouS = Float.parseFloat(item.getXiaoshouScount());
						} catch (Exception e) {
							xiaoshou = 0f;
							xiaoshouS = 0f;
						}
					}
					if(item.getJudge().contains("调进")){
						try {
							diaojing = Float.parseFloat(item.getDiaojing());
							diaojingS = Float.parseFloat(item.getDiaojingScount());
						} catch (Exception e) {
							diaojing = 0f;
							diaojingS = 0f;
						}
					}
					//甲方
					if(item.getJudge().contains("纯销")){
						try {
							cunxiao = Float.parseFloat(item.getCunxiao());
							cunxiaoS = Float.parseFloat(item.getCunxiaoScount());
						} catch (Exception e) {
							cunxiao = 0f;
							cunxiaoS = 0f;
						}
					}
					if(item.getJudge().contains("调出")){
						try {
							diaochu = Float.parseFloat(item.getDiaochu());
							diaochuS = Float.parseFloat(item.getDiaochuScount());
						} catch (Exception e) {
							diaochu = 0f;
							diaochuS = 0f;
						}
					}
				}
			}
			//for循环遍历完后，把所有相等的item都拎出来，把期初、销售、调进、调出、纯销计算出来
			float kucun = qichu+xiaoshou+diaojing-cunxiao-diaochu;
			float kucunS = qichuS+xiaoshouS+diaojingS-cunxiaoS-diaochuS;
			all.setEtime(etime);
			all.setQichu(qichu+"");
			all.setQichuScount(qichuS+"");
			all.setXiaoshou(xiaoshou+"");
			all.setXiaoshouScount(xiaoshouS+"");
			all.setDiaojing(diaojing+"");
			all.setDiaojingScount(diaojingS+"");
			all.setCunxiao(cunxiao+"");
			all.setCunxiaoScount(cunxiaoS+"");
			all.setDiaochu(diaochu+"");
			all.setDiaochuScount(diaochuS+"");
			all.setKucun(kucun+"");
			all.setKucunScount(kucunS+"");
			resultItems.add(all);
			/***
			 * 把所有不重复的库存项中，拧出来小包、自营模式的库存项
			 */
			KuCunItem e = new KuCunItem(all.getCompany(),all.getProduct(),all.getPack(),all.getPmode(),all.getTx());
			e.setEtime(all.getEtime());
			if(all.getPmode().contains("小包") || all.getPmode().equals("自营")){
				if(!resultItems_mid.contains(e)){
					resultItems_mid.add(e);
				}
			} 
		}
		/***
		 * 再次循环迭代所有的不重复的库存项，把小包和自营的合并客户，得到唯一库存项
		 */
		for(KuncunListItem item:resultItems){
			//非小包、非自营 的不需要合并
			if(!item.getPmode().contains("小包") && !item.getPmode().equals("自营")){
				resultItems_last.add(item);
			} else {
				resultItems_mid_xiaobao.add(item);
			}
		}
		/***
		 * 循环迭代所有不重复的小包和自营的库存项
		 * //合并小包、自营 的
		 * 客户：合并统一为商业公司
		 */
		for(KuCunItem all:resultItems_mid){
			Float qichu = 0f;
			Float xiaoshou = 0f;
			Float diaojing = 0f;
			Float cunxiao = 0f;
			Float diaochu = 0f;
			
			Float sum_qichu = 0f;
			Float sum_xiaoshou = 0f;
			Float sum_diaojing = 0f;
			Float sum_cunxiao = 0f;
			Float sum_diaochu = 0f;
			
			Float qichuS = 0f;
			Float xiaoshouS = 0f;
			Float diaojingS = 0f;
			Float cunxiaoS = 0f;
			Float diaochuS = 0f;
			
			Float sum_qichuS = 0f;
			Float sum_xiaoshouS = 0f;
			Float sum_diaojingS = 0f;
			Float sum_cunxiaoS = 0f;
			Float sum_diaochuS = 0f;
			
			KuncunListItem xiaobaoItem = new KuncunListItem();
			for(KuncunListItem item:resultItems_mid_xiaobao){
				if(all.getComplany().equals(item.getCompany())
						&&all.getProduct().equals(item.getProduct())
						&&all.getMode().equals(item.getPmode())
						&&all.getPack().equals(item.getPack())){
					try {
						qichu = Float.parseFloat(item.getQichu());
						qichuS = Float.parseFloat(item.getQichuScount());
					} catch (Exception e) {
						qichu = 0f;
						qichuS = 0f;
					}
					try {
						xiaoshou = Float.parseFloat(item.getXiaoshou());
						xiaoshouS = Float.parseFloat(item.getXiaoshouScount());
					} catch (Exception e) {
						xiaoshou = 0f;
						xiaoshouS = 0f;
					}
					try {
						diaojing = Float.parseFloat(item.getDiaojing());
						diaojingS = Float.parseFloat(item.getDiaojingScount());
					} catch (Exception e) {
						diaojing = 0f;
						diaojingS = 0f;
					}
					try {
						cunxiao = Float.parseFloat(item.getCunxiao());
						cunxiaoS = Float.parseFloat(item.getCunxiaoScount());
					} catch (Exception e) {
						cunxiao = 0f;
						cunxiaoS = 0f;
					}
					try {
						diaochu = Float.parseFloat(item.getDiaochu());
						diaochuS = Float.parseFloat(item.getDiaochuScount());
					} catch (Exception e) {
						diaochu = 0f;
						diaochuS = 0f;
					}
					sum_qichu+=qichu;
					sum_xiaoshou+=xiaoshou;
					sum_diaojing+=diaojing;
					sum_cunxiao+=cunxiao;
					sum_diaochu+=diaochu;
					
					sum_qichuS+=qichuS;
					sum_xiaoshouS+=xiaoshouS;
					sum_diaojingS+=diaojingS;
					sum_cunxiaoS+=cunxiaoS;
					sum_diaochuS+=diaochuS;
				}
			}
			xiaobaoItem.setEtime(all.getEtime());
			xiaobaoItem.setCompany(all.getComplany());
			xiaobaoItem.setProvince(map.get(all.getComplany()));
			xiaobaoItem.setCompanyID(mapID.get(all.getComplany()));
			xiaobaoItem.setPmode(all.getMode());
			xiaobaoItem.setTx(all.getTx());
			xiaobaoItem.setClient(all.getComplany());
			xiaobaoItem.setProduct(all.getProduct());
			xiaobaoItem.setPack(all.getPack());
			xiaobaoItem.setQichu(sum_qichu+"");
			xiaobaoItem.setQichuScount(sum_qichuS+"");
			xiaobaoItem.setXiaoshou(sum_xiaoshou+"");
			xiaobaoItem.setXiaoshouScount(sum_xiaoshouS+"");
			xiaobaoItem.setDiaojing(sum_diaojing+"");
			xiaobaoItem.setDiaojingScount(sum_diaojingS+"");
			xiaobaoItem.setCunxiao(sum_cunxiao+"");
			xiaobaoItem.setCunxiaoScount(sum_cunxiaoS+"");
			xiaobaoItem.setDiaochu(sum_diaochu+"");
			xiaobaoItem.setDiaochuScount(sum_diaochuS+"");
			
			float sum_kucun = sum_qichu+sum_xiaoshou+sum_diaojing-sum_cunxiao-sum_diaochu;
			float sum_kucunS = sum_qichuS+sum_xiaoshouS+sum_diaojingS-sum_cunxiaoS-sum_diaochuS;
			xiaobaoItem.setKucun(sum_kucun+"");
			xiaobaoItem.setKucunScount(sum_kucunS+"");
			resultItems_last.add(xiaobaoItem);
		} 
		return resultItems_last;
	}
	/***
	 * 计算时间理论库存
	 * @param year 当前年
	 * @param etime 截止时间
	 * @param map 存放了以商业公司为key,vlaue=省份
	 * @param mapID 存放了以商业公司为key,vlaue=是否是ID账号商业 标识
	 * @param listYifan 当前年 所有的乙方集合
	 * @param listJiafan 当前年 所有的甲方集合
	 * @return
	 * @throws Exception
	 */
	public static List<KuncunListItem> calculateKuCun2(String year,String etime,Map<String,String> map,Map<String,String> mapID,List<Plan> listYifan,List<Plan> listJiafan) throws Exception{
		//获取所有需要参加计算的商业公司或客户，包括小包和预付的，考虑充当过乙方的公司，只充当了甲方没充当乙方为无效数据
		List<KuncunListItem> resultItems_last = new ArrayList<KuncunListItem>(Constant.SMALL_CAPACITY*8);
		List<KuCunItem> resultItems_mid = new ArrayList<KuCunItem>(Constant.SMALL_CAPACITY*8);
		List<KuncunListItem> resultItems_mid_xiaobao = new ArrayList<KuncunListItem>(Constant.SMALL_CAPACITY*8);
		List<KuncunListItem> resultItems = new ArrayList<KuncunListItem>(Constant.SMALL_CAPACITY*8);
		List<KuncunListItem> items = new ArrayList<KuncunListItem>(Constant.SMALL_CAPACITY*8);
		List<KuncunListItem> allItems = new ArrayList<KuncunListItem>(Constant.SMALL_CAPACITY*8);
		
		for(Plan plan:listYifan){
			String terminal = plan.getTerminal();
			String product = plan.getProduct();
			String pack = plan.getPack();
			String province = map.get(terminal);
			String complanID = mapID.get(terminal);
			String mode = plan.getMode();
			String client = plan.getClient();
			String judge = plan.getJudge();
			String count = plan.getCount();
			String tx = plan.getXieyizhuangtai();
//			String tx = "Rx";
//			if(pack.equals("20") || pack.equals("30") || pack.equals("40")) {
//				tx = "OTC";
//			}
			KuncunListItem item = new KuncunListItem(terminal,product,pack,mode,tx,client);
			if(judge.equals("期初")){
				item.setQichu(count);
				item.setJudge("期初");
			}
			if(judge.equals("销售")){
				item.setXiaoshou(count);
				item.setJudge("销售");
			}
			if(judge.equals("调拨")){
				item.setDiaojing(count);
				item.setJudge("调进");
			}
			item.setProvince(province);
			item.setCompanyID(complanID);
			
			//乙方存放明细项
			items.add(item);
			//所有不重复的item：公司+品种+包装+模式+客户+条线
			if(!allItems.contains(item)){
				allItems.add(item);
			}
		}
		//long end = System.currentTimeMillis();
		//System.out.println("查询乙方："+(end-start)/1000);
		//start=System.currentTimeMillis();
		for(Plan plan:listJiafan){
			String commercial1 = plan.getCommercial1();
			String product = plan.getProduct();
			String pack = plan.getPack();
			String province = map.get(commercial1);
			String complanID = mapID.get(commercial1);
			String mode = plan.getMode();
			String client = plan.getClient();
			String judge = plan.getJudge();
			String count = plan.getCount();
			String tx = plan.getXieyizhuangtai();
//			String tx = "Rx";
//			if(pack.equals("20") || pack.equals("30") || pack.equals("40")) {
//				tx = "OTC";
//			}
			KuncunListItem item = new KuncunListItem(commercial1,product,pack,mode,tx,client);
			if(judge.equals("纯销")){
				item.setCunxiao(count);
				item.setJudge("纯销");
			}
			if(judge.equals("调拨")){
				item.setDiaochu(count);
				item.setJudge("调出");
			}
			item.setProvince(province);
			item.setCompanyID(complanID);
			//甲方存放明细项 公司+品种+包装+模式+客户+条线
			items.add(item);
			if(!allItems.contains(item)){
				allItems.add(item);
			}
		}
		//System.out.println("items.size:"+items.size());
		//end=System.currentTimeMillis();
		//System.out.println("查询甲方："+(end-start)/1000);
		//start=System.currentTimeMillis();
		/***
		 * 循环迭代所有的不重复的库存项，对各个库存项的字段进行初始化
		 * 这些不重复的库存项决定了下载后库存数据的行数
		 */
		for(KuncunListItem all:allItems){
			Float qichu = 0f;
			Float xiaoshou = 0f;
			Float diaojing = 0f;
			Float cunxiao = 0f;
			Float diaochu = 0f;
			for(KuncunListItem item:items){//所有库存项
				/***
				 * 非小包、非自营 都是按照公司+品种+包装+模式+客户 确定唯一项 
				 */
				if(all.getCompany().equals(item.getCompany())
						&&all.getProduct().equals(item.getProduct())
						&&all.getPack().equals(item.getPack())
						&&all.getClient().equals(item.getClient())
						&&all.getPmode().equals(item.getPmode())){
					//乙方
					if(item.getJudge().contains("期初")){
						try {
							qichu = Float.parseFloat(item.getQichu());
						} catch (Exception e) {
							qichu = 0f;
						}
					}
					if(item.getJudge().contains("销售")){
						try {
							xiaoshou = Float.parseFloat(item.getXiaoshou());
						} catch (Exception e) {
							xiaoshou = 0f;
						}
					}
					if(item.getJudge().contains("调进")){
						try {
							diaojing = Float.parseFloat(item.getDiaojing());
						} catch (Exception e) {
							diaojing = 0f;
						}
					}
					//甲方
					if(item.getJudge().contains("纯销")){
						try {
							cunxiao = Float.parseFloat(item.getCunxiao());
						} catch (Exception e) {
							cunxiao = 0f;
						}
					}
					if(item.getJudge().contains("调出")){
						try {
							diaochu = Float.parseFloat(item.getDiaochu());
						} catch (Exception e) {
							diaochu = 0f;
						}
					}
				}
			}
			//for循环遍历完后，把所有相等的item都拎出来，把期初、销售、调进、调出、纯销计算出来
			float kucun = qichu+xiaoshou+diaojing-cunxiao-diaochu;
			all.setEtime(etime);
			all.setQichu(qichu+"");
			all.setQichuScount(InitPlansUtil.getScount(all.getTx(),all.getProduct(),all.getPack(),qichu+""));
			all.setXiaoshou(xiaoshou+"");
			all.setXiaoshouScount(InitPlansUtil.getScount(all.getTx(),all.getProduct(),all.getPack(),xiaoshou+""));
			all.setDiaojing(diaojing+"");
			all.setDiaojingScount(InitPlansUtil.getScount(all.getTx(),all.getProduct(),all.getPack(),diaojing+""));
			all.setCunxiao(cunxiao+"");
			all.setCunxiaoScount(InitPlansUtil.getScount(all.getTx(),all.getProduct(),all.getPack(),cunxiao+""));
			all.setDiaochu(diaochu+"");
			all.setDiaochuScount(InitPlansUtil.getScount(all.getTx(),all.getProduct(),all.getPack(),diaochu+""));
			all.setKucun(kucun+"");
			all.setKucunScount(InitPlansUtil.getScount(all.getTx(),all.getProduct(),all.getPack(),kucun+""));
			resultItems.add(all);
			/***
			 * 把所有不重复的库存项中，拧出来小包、自营模式的库存项
			 */
			KuCunItem e = new KuCunItem(all.getCompany(),all.getProduct(),all.getPack(),all.getPmode(),all.getTx());
			e.setEtime(all.getEtime());
			if(all.getPmode().equals("小包") || all.getPmode().equals("自营")){
				//存放小包类型的 商业+品种+包装+模式+条线 唯一
				if(!resultItems_mid.contains(e)){
					resultItems_mid.add(e);
				}
			} 
		}
		/***
		 * 再次循环迭代所有的不重复的库存项，把小包和自营的合并客户，得到唯一库存项
		 */
		for(KuncunListItem item:resultItems){
			//非小包、非自营 的不需要合并
			if(!item.getPmode().equals("小包") && !item.getPmode().equals("自营")){
				resultItems_last.add(item);
			} else {
				resultItems_mid_xiaobao.add(item);
			}
		}
		/***
		 * 循环迭代所有不重复的小包和自营的库存项
		 * //合并小包、自营 的
		 * 客户：合并统一为商业公司
		 */
		for(KuCunItem all:resultItems_mid){
			Float qichu = 0f;
			Float xiaoshou = 0f;
			Float diaojing = 0f;
			Float cunxiao = 0f;
			Float diaochu = 0f;
			Float sum_qichu = 0f;
			Float sum_xiaoshou = 0f;
			Float sum_diaojing = 0f;
			Float sum_cunxiao = 0f;
			Float sum_diaochu = 0f;
			KuncunListItem xiaobaoItem = new KuncunListItem();
			for(KuncunListItem item:resultItems_mid_xiaobao){
				if(all.getComplany().equals(item.getCompany())
						&&all.getProduct().equals(item.getProduct())
						&&all.getMode().equals(item.getPmode())
						&&all.getPack().equals(item.getPack())){
					try {
						qichu = Float.parseFloat(item.getQichu());
					} catch (Exception e) {
						qichu = 0f;
					}
					try {
						xiaoshou = Float.parseFloat(item.getXiaoshou());
					} catch (Exception e) {
						xiaoshou = 0f;
					}
					try {
						diaojing = Float.parseFloat(item.getDiaojing());
					} catch (Exception e) {
						diaojing = 0f;
					}
					try {
						cunxiao = Float.parseFloat(item.getCunxiao());
					} catch (Exception e) {
						cunxiao = 0f;
					}
					try {
						diaochu = Float.parseFloat(item.getDiaochu());
					} catch (Exception e) {
						diaochu = 0f;
					}
					sum_qichu+=qichu;
					sum_xiaoshou+=xiaoshou;
					sum_diaojing+=diaojing;
					sum_cunxiao+=cunxiao;
					sum_diaochu+=diaochu;
				}
			}
			xiaobaoItem.setEtime(all.getEtime());
			xiaobaoItem.setCompany(all.getComplany());
			xiaobaoItem.setProvince(map.get(all.getComplany()));
			xiaobaoItem.setCompanyID(mapID.get(all.getComplany()));
			xiaobaoItem.setPmode(all.getMode());
			xiaobaoItem.setTx(all.getTx());
			xiaobaoItem.setClient(all.getComplany());
			xiaobaoItem.setProduct(all.getProduct());
			xiaobaoItem.setPack(all.getPack());
			xiaobaoItem.setQichu(sum_qichu+"");
			xiaobaoItem.setQichuScount(InitPlansUtil.getScount(all.getTx(),all.getProduct(),all.getPack(),sum_qichu+""));
			xiaobaoItem.setXiaoshou(sum_xiaoshou+"");
			xiaobaoItem.setXiaoshouScount(InitPlansUtil.getScount(all.getTx(),all.getProduct(),all.getPack(),sum_xiaoshou+""));
			xiaobaoItem.setDiaojing(sum_diaojing+"");
			xiaobaoItem.setDiaojingScount(InitPlansUtil.getScount(all.getTx(),all.getProduct(),all.getPack(),sum_diaojing+""));
			xiaobaoItem.setCunxiao(sum_cunxiao+"");
			xiaobaoItem.setCunxiaoScount(InitPlansUtil.getScount(all.getTx(),all.getProduct(),all.getPack(),sum_cunxiao+""));
			xiaobaoItem.setDiaochu(sum_diaochu+"");
			xiaobaoItem.setDiaochuScount(InitPlansUtil.getScount(all.getTx(),all.getProduct(),all.getPack(),sum_diaochu+""));
			float sum_kucun = sum_qichu+sum_xiaoshou+sum_diaojing-sum_cunxiao-sum_diaochu;
			xiaobaoItem.setKucun(sum_kucun+"");
			xiaobaoItem.setKucunScount(InitPlansUtil.getScount(all.getTx(),all.getProduct(),all.getPack(),sum_kucun+""));
			resultItems_last.add(xiaobaoItem);
		} 
		return resultItems_last;
	}
	
	public static void synchronizationPlan(SynchronizationService synchronizationService,List<Plan> list) throws Exception{
		//获取更新的省份、地市、区县，用于同步更新
		Set<String> provinces = new HashSet<String>(Constant.INIT_CAPACITY*4);
		Set<String> citys = new HashSet<String>(Constant.SMALL_CAPACITY);
		Set<String> countrys = new HashSet<String>(Constant.SMALL_CAPACITY);
		if(list != null && list.size()>0) {
			for (Plan p : list) {
				//获取更新的省份、地市、区县，用于同步更新/
				provinces.add(p.getProvince());
				citys.add(p.getCity());
				countrys.add(p.getCounty());
			}
			//同步更新流向 
			synchronizationService.syncUpdatePlansAndUpdateXsCount(provinces, citys, countrys);
		}
	}
	
	/***
	 * 初始化产品成本,下面的cost成本，同时注意修改ExpireJobTask中的
	 * @param product
	 * @param pack
	 * @return
	 */
	public static String initProductCost(String product,String pack) {
		String cost = "0";
		if("A".equals(product)) {
			if("12".equals(pack)) {
				cost = Constant.COST_A12;
			}
			if("24".equals(pack)) {
				cost = Constant.COST_A24;
			}
			if("240".equals(pack)) {
				cost = Constant.COST_A240;
			}
			if("36".equals(pack)) {
				cost = Constant.COST_A36;
			}
			if("48".equals(pack)) {
				cost = Constant.COST_A48;
			}
			if("480".equals(pack)) {
				cost = Constant.COST_A480;
			}
			if("20".equals(pack)) {
				cost = Constant.COST_A20;
			}
			if("30".equals(pack)) {
				cost = Constant.COST_A30;
			}
			if("40".equals(pack)) {
				cost = Constant.COST_A40;
			}
		}
		if("Y".equals(product)) {
			if("24".equals(pack)) {
				cost = Constant.COST_Y24;
			}
			if("36".equals(pack)) {
				cost = Constant.COST_Y36;
			}
			if("20".equals(pack)) {
				cost = Constant.COST_Y20;
			}
			if("30".equals(pack)) {
				cost = Constant.COST_Y30;
			}
			if("40".equals(pack)) {
				cost = Constant.COST_Y40;
			}
		}
		if("Z".equals(product)) {
			if("48".equals(pack)) {
				cost = Constant.COST_Z48;
			}
			if("20".equals(pack)) {
				cost = Constant.COST_Z20;
			}
			if("30".equals(pack)) {
				cost = Constant.COST_Z30;
			}
			if("24".equals(pack)) {
				cost = Constant.COST_Z24;
			}
			if("36".equals(pack)) {
				cost = Constant.COST_Z36;
			}
			if("40".equals(pack)) {
				cost = Constant.COST_Z40;
			}
		}
		if("B".equals(product)) {
			if("5".equals(pack)) {
				cost = Constant.COST_B5;
			}
			if("10".equals(pack)) {
				cost = Constant.COST_B10;
			}
		}
		return cost;
	}
	
}
